package org.lex.io;

import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;

public class CountingInputStream2 extends FilterInputStream {
	private volatile long readBytesCount = 0L;

	public CountingInputStream2(InputStream in) {
		super(in);
	}

	public long getReadBytesCount() {
		return this.readBytesCount;
	}

	public void resetCounter() {
		this.readBytesCount = 0L;
	}

	@Override
	public int available() throws IOException {
		return super.available();
	}

	@Override
	public void close() throws IOException {
		super.close();
	}

	@Override
	public synchronized void mark(int readlimit) {
		super.mark(readlimit);
	}

	@Override
	public boolean markSupported() {
		return super.markSupported();
	}

	@Override
	public int read() throws IOException {
		return this.readOneByte();
	}

	@Override
	public int read(byte[] b, int off, int len) throws IOException {
		if (b == null)
			throw new NullPointerException();
		else if (off < 0 || len < 0 || len > b.length - off)
			throw new IndexOutOfBoundsException();
		else if (len == 0)
			return 0;
		// ==============
		int ch = this.readOneByte();
		if (ch == -1)
			return -1;
		b[off] = (byte) ch;
		int i = 1;
		try {
			for (; i < len; i++) {
				ch = this.readOneByte();
				if (ch == -1) {
					break;
				}
				b[off + i] = (byte) ch;
			}
		} catch (IOException ee) {
		}
		return i;
	}

	@Override
	public int read(byte[] b) throws IOException {
		return this.read(b, 0, b.length);
	}

	private int readOneByte() throws IOException {
		int ch = super.read();
		// XXX do we need to check (ch eq -1)?
		// if( -1 != ch )
		readBytesCount++;
		return ch;
	}

	@Override
	public synchronized void reset() throws IOException {
		super.reset();
	}

	@Override
	public long skip(long n) throws IOException {
		return super.skip(n);
	}
}
